package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.AccessInspection;
import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.LoginObj;
import com.cndw.kungfu.comm.tencent.LoginObjQQ;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.event.model.PlayerLoginInitHandler;
import com.cndw.kungfu.ext.LangConfigLib;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.PropertiesLib;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.player.PlayerManager;
import com.cndw.kungfu.model.scene.SubLineCore;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.annotation.UnAuth;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;
import com.cndw.rpg.framework.SessionHolder;

/**
 * 登录,注册
 * 
 * @author fantadust
 * 
 */
@Controller
public class LoginController {

	
	@Autowired
	private PlayerManager playerManager;

	private static Map<String, Object> sysConfigMap;
	private static byte[] lock = new byte[1];

	/**
	 * 身份验证
	 * 
	 * @param message
	 * @param player
	 */
	@UnAuth
	public ResponseMessage auth(Session session, Map<String, Object> loginMap) {
		if (session == null || session.isLogin()) {
			return null;
		}
		
		if (loginMap == null || loginMap.isEmpty()) {
			LogUtil.getMain().debug("login Map err");
			return null;
		}
		LoginObj loginObj = new LoginObjQQ(loginMap);
		if (loginObj.isLostArgs()) {
			LogUtil.getMain().debug("login arg lost  " + loginObj.info());
			return null;
		}
		int currentTime = TimeProcesser.getUnixTime();
		String accountName = loginObj.getOpenId();
		if (accountName == null || accountName.length() == 0) {
			LogUtil.getMain().debug("login err accountName");
			return null;
		}

		if (!ConstantsConfig.isLocalHost()) {
			if (loginObj.isExpir()) {
				LogUtil.getMain().debug("longin time err " + accountName + " : " + (currentTime - loginObj.getTime()));
				return ResponseMessage.errMsg(LanguageLib.get("login.auth.timeout"));
			}
			if (!loginObj.isPass()) {
				LogUtil.getMain().debug("longin sign err " + loginObj.info());
				return null;
			}
		}

		if (ConstantsConfig.isSysClosed() && !AccessInspection.isGmAccountName(accountName)) {
			return ResponseMessage.errMsg(LanguageLib.get("comm.sys.close"));
		}
		/**
		 * 验证密钥之类
		 */
		Map<String, Object> map = new HashMap<String, Object>();
		long playerId = Context.getPlayerServer().getPlayerIdByAccount(accountName);
		map.put("playerId", playerId);
		if (playerId <= 0) {

			map.put("noReg", 1);// 提示未注册
			playerManager.logRegInsert(accountName, currentTime);// 做数据采集日志
			
			QQDC.getInstance().logClick(loginObj,session.getRemoteAddress(),LogFieldType.loginNew);

		} else {
			Player player = Context.getPlayerServer().getByPlayerId(playerId);			
			session.setStatus(Session.PLAY_STATUS_AUTHED);// 登录成功的验证
			SessionHolder.getInstance().put(player.getPlayerId(), session);
			
			loginObj.syncContent(player);//在腾讯平台时候更新用户黄钻信息			
			PlayerLoginInitHandler handler = new PlayerLoginInitHandler(player, false);
			Context.getTimerServer().execute(handler);
			player.setLastLogin(currentTime);
			player.setLastIp(session.getRemoteAddress());
			player.commitSync();// 提交同步
			player.getDataInfo().setLastSceneId(0);// 上次场景做清理

	
			

			// 把之前的踢掉
			map.put("logined", 1);
			map.put("player", player.toPlayerVO());
			if (ConstantsConfig.isSysInspectAddicted()) {// 检查防沉迷
				if (!player.getDataInfo().isPassAddicted()) {
					if (loginObj.isAl()) {
						player.getDataInfo().setPassAddicted(true);
					} else {
						map.put("noPassAddicted", true);
						map.put("todayOnLine", player.getTodayOnLine());
					}
				}
			}

		}
		session.setUidAndAccountName(playerId, accountName);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 注册用户
	 * 
	 * @param session
	 * @param playerName
	 *            角色名称
	 * @param vocationId
	 *            职业id
	 * @return
	 */
	@UnAuth
	public ResponseMessage userReg(Session session, String playerName, int vocationId, Map<String, Object> loginMap) {
		if (session.getUid() > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.havareg"));
		} else if (session.getAccountName() == null) {// 防止未登录直接注册
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		// 这里要检测是否已创建
		if (StringUtils.isBlank(playerName)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.needUserName"));
		}
		int nameLength = playerName.getBytes(Constants.charset).length;
		if (nameLength < ConstantsConfig.getNameLength() || nameLength > ConstantsConfig.getNameLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.nameLengthErr", ConstantsConfig.getNameLength(), ConstantsConfig.getNameLengthMax()));
		} else if (vocationId <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.vocationIdErr"));
		} else if (!WordProcesser.chkPerg(playerName, ConstantsConfig.getCommCreateNameExp())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.nameReg"));
		}
		String bad = WordProcesser.chkBadWorlds(playerName);
		if (bad != null ) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.name.bad",bad));
		}

		if (playerManager.getPlayerIdByPlayerName(playerName) > 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("login.overreg"));
		}
		LoginObj loginObj = new LoginObjQQ(loginMap);
		if (!ConstantsConfig.isLocalHost() && !loginObj.isPass()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		String platform = loginObj.getPf();

		Player player = playerManager.insert(session.getAccountName(), playerName, vocationId, session.getRemoteAddress(), platform);
		if (player == null || player.getPlayerId() == 0) {
			long oldPlayerId = Context.getPlayerServer().getPlayerIdByAccount(session.getAccountName());
			if (oldPlayerId > 0) {
				player = Context.getPlayerServer().getByPlayerId(oldPlayerId);
				//return ResponseMessage.ticpErrMsg(LanguageLib.get("login.havareg"));
			}
			if (player == null || player.getPlayerId() == 0 || !player.getAccountName().equals(session.getAccountName())) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.sys"));
			}
		}
	
		Context.getCacheCenter().putPlayer(player);// 加多次无意义的转化,防止意外冲突
		player = Context.getPlayerServer().getByPlayerId(player.getPlayerId());
		// 再一次更新session
		session.setStatus(Session.PLAY_STATUS_AUTHED);// 登录成功的验证
		session.setUidAndAccountName(player.getPlayerId(), session.getAccountName());
		// 发新手礼包
		Context.getGoodsServer().giveGoods(player.getPlayerId(), 103508, 1);
		//在腾讯平台时候更新用户黄钻信息
		loginObj.syncContent(player);
		
		// 启动玩家登录事件
		PlayerLoginInitHandler handler = new PlayerLoginInitHandler(player, true);
		Context.getTimerServer().execute(handler);

		// 加入到总集合
		SessionHolder.getInstance().put(player.getPlayerId(), session);

		// 把职业注册数量更新到内存
		AtomicIntegerArray vocationCounts = Context.getPlayerServer().getVocationCounts();
		vocationCounts.getAndIncrement(vocationId - 1);

		

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("player", player.toPlayerVO());

		if (ConstantsConfig.isSysInspectAddicted()) {// 检查防沉迷
			if (!player.getDataInfo().isPassAddicted()) {
				if (loginObj.isAl()) {
					player.getDataInfo().setPassAddicted(true);
				} else {
					map.put("noPassAddicted", true);
					map.put("todayOnLine", 0);
				}
			}
		}
		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 获取角色创建资料
	 * 
	 * @param session
	 * @return
	 */
	@UnAuth
	public ResponseMessage getVocationList(Session session) {
		// Collection<Vocation> vocations =
		// Context.getCongfigServer().getVocations();

		AtomicIntegerArray vocationCounts = Context.getPlayerServer().getVocationCounts();
		int vocationId = 0;
		if (vocationCounts.get(1) < vocationCounts.get(0)) {
			vocationId = 1;
		}
		if (vocationCounts.get(2) < vocationCounts.get(vocationId)) {
			vocationId = 2;
		}
		vocationId++;

		Map<String, Object> map = new HashMap<String, Object>();
		// map.put("vocations", vocations);
		map.put("vocationId", vocationId);
		if (session.getAccountName() != null) {
			playerManager.logRegUpdate(session.getAccountName(), 2);// 数据采集

		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 随机一个角色名称给客户端
	 * 
	 * @param session
	 * @param sex
	 * @return
	 */
	@UnAuth
	public ResponseMessage getRandName(Session session, int sex) {
		Map<String, Object> map = new HashMap<String, Object>();

		String randName = "";
		int t = 0;
		do {
			t++;
			String bodyname = "";
			String surName = PropertiesLib.getArrayValue("playName", "surName");
			if (sex == 1) {
				bodyname = PropertiesLib.getArrayValue("playName", "boyName");
			} else {
				bodyname = PropertiesLib.getArrayValue("playName", "girlName");
			}
			randName = surName + bodyname;
			if (t > 10)
				break;

		} while (playerManager.getPlayerIdByPlayerName(randName) > 0);

		map.put("name", randName);
		map.put("times", t);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 进入游戏时候加载的通用配置
	 * 
	 * @param session
	 * @return
	 */
	@UnAuth
	public ResponseMessage loadSysConfig(Session session) {
		if (sysConfigMap == null) {
			synchronized (lock) {
				if (sysConfigMap == null) {
					sysConfigMap = new HashMap<String, Object>();
					sysConfigMap.put("vocationNames", Context.getCongfigServer().getVocationNames());
					sysConfigMap.put("unionJobsName", LangConfigLib.getConfigs("config.union.job"));
					sysConfigMap.put("unionPermsName", LangConfigLib.getConfigs("config.union.permission"));
					sysConfigMap.put("sysSubLinePlayers", ConstantsConfig.getSysSubLinePlayers());
					sysConfigMap.put("chatIntervalSeconds", ConstantsConfig.getChatIntervalSeconds());
					sysConfigMap.put("sysCgServiceId", ConstantsConfig.getSysCgServiceId());
					sysConfigMap.put("sysCgSvrId", ConstantsConfig.getSysCgSvrId());
					sysConfigMap.put("chatLengthMax", ConstantsConfig.getChatLengthMax());
					sysConfigMap.put("partnerEName", ConstantsConfig.getSysCgPartnerEName());
					sysConfigMap.put("sysPetNames", Context.getPetServer().getPetNames());
					sysConfigMap.put("sysInstructor", ConstantsConfig.getSysInstructor());
					sysConfigMap.put("sysLineFlow", SubLineCore.getOverFlowNum());
					sysConfigMap.put("sysCgOpenTime", ConstantsConfig.getSysCgOpenTime());
					
				}
			}

		}

		return ResponseMessage.getSuccMessage(sysConfigMap);
	}

	public static void clearConfigMap() {
		synchronized (lock) {
			sysConfigMap = null;
			LogUtil.getMain().debug("clear sysConfigMap");
		}
	}

	/**
	 * 心跳检测
	 * 
	 * @param session
	 * @return
	 */
	@UnAuth
	public ResponseMessage idleMessage(Session session) {
		return null;
	}
	/**
	 * 腾讯平台,opkey续期
	 * @param session
	 * @return
	 */
	public ResponseMessage openkeyRenewal(Session session){
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player != null && !player.getDataInfo().isGmLogin()) {
			CommInspection.isLogin(player);
		}
		return null;
	}

}
